package com.voute.View.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.umeng.analytics.MobclickAgent;
import com.voute.Api.FocusTagsService;
import com.voute.Api.PushMessageService;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Base.BaseFragment;
import com.voute.Model.Action.ExitAppAction;
import com.voute.Model.Action.StartRefreshTagsAction;
import com.voute.Model.Bean.BaseBean;
import com.voute.Model.Bean.FeedCirclePushMessageBean;
import com.voute.Model.Bean.FeedCirclePushMessageEntity;
import com.voute.Model.Bean.TagsBean;
import com.voute.R;
import com.voute.Utils.CommonSubscriber;
import com.voute.Utils.PreferenceUtils;
import com.voute.Utils.RxBus;
import com.voute.Utils.ServiceFactory;
import com.voute.Utils.TransformUtils;
import com.voute.Utils.ViewUtils;
import com.voute.View.Fragement.DiscoveryFragment;
import com.voute.View.Fragement.PersonalInfoFragment;
import com.voute.View.IView.IMainView;
import com.zxinsight.MLink;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;

//@MLinkDefaultRouter
public class MainActivity extends BaseActivity implements IMainView {

    private FragmentManager mFragmentManager;
    //发现以及本地Fragment
//    BaseFragment mDiscoveryLocalFragment;
    BaseFragment mCircleFragment;
    BaseFragment meFragment;
    BaseFragment mUpdateTodayFragment;
    BaseFragment currentFragment;
    BaseFragment mChannelFragment;
    BaseFragment mArticalFragment;
    FrameLayout content_frame;
    BottomNavigationBar bottom_navigation_bar;
    RadioGroup radio_group_bottom;
    RadioButton radio_btn_bottom_home;
    RadioButton radio_btn_bottom_me;
    Button btn_new_feed_bottom;
    private Subscription rxSubscription;
    Subscription rxSubscription_long;
    private int current_fragment_index = 0;
    private TextView notify_tv_bottom;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void setupView() {
        content_frame = $(R.id.content_frame);
        btn_new_feed_bottom = $(R.id.btn_new_feed_bottom);
        radio_group_bottom = $(R.id.radio_group_bottom);
        bottom_navigation_bar = $(R.id.bottom_navigation_bar);
        radio_btn_bottom_home = $(R.id.radio_btn_bottom_home);
        radio_btn_bottom_me = $(R.id.radio_btn_bottom_me);
        notify_tv_bottom = $(R.id.notify_tv_bottom);
        mFragmentManager = getSupportFragmentManager();
        rxSubscription = RxBus.getDefault().toObservable(ExitAppAction.class).subscribe(new Action1<ExitAppAction>() {
            @Override
            public void call(ExitAppAction exitAppAction) {
                radio_btn_bottom_home.setChecked(true);
                radio_btn_bottom_me.setChecked(false);
                mFragmentManager.beginTransaction().hide(currentFragment).show(mCircleFragment).commitAllowingStateLoss();
                currentFragment = mCircleFragment;
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });

        radio_btn_bottom_home.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    current_fragment_index = 0;
                    radio_btn_bottom_me.setChecked(false);
                    mFragmentManager.beginTransaction().hide(currentFragment).show(mCircleFragment).commitAllowingStateLoss();
                    currentFragment = mCircleFragment;
                }
            }
        });

        radio_btn_bottom_me.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked) {
                    if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                        radio_btn_bottom_home.setChecked(true);
                        current_fragment_index = 0;
                        radio_btn_bottom_me.setChecked(false);
                        Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                        MainActivity.this.startActivity(intent);
                    } else {
                        current_fragment_index = 1;
                        if (meFragment == null) {
                            meFragment = ViewUtils.createFragment(PersonalInfoFragment.class, false);
                            mFragmentManager.beginTransaction().hide(currentFragment).add(R.id.content_frame, meFragment).commitAllowingStateLoss();
                        } else {
                            mFragmentManager.beginTransaction().hide(currentFragment).show(meFragment).commitAllowingStateLoss();
                        }
                        currentFragment = meFragment;
                        radio_btn_bottom_home.setChecked(false);
                    }
                }
            }
        });

        btn_new_feed_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                    Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                    MainActivity.this.startActivity(intent);
                } else {
                    MobclickAgent.onEvent(MainActivity.this, " create_feed_start");
                    Intent intent = new Intent(MainActivity.this, CreateFeedActivity.class);
                    MainActivity.this.startActivity(intent);
                }
            }
        });
        EventBus.getDefault().register(this);
        MLink.getInstance(this).deferredRouter();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    public void onEvent(StartRefreshTagsAction startRequestTags) {
        if (!TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
            ServiceFactory.GetInstance().createService(FocusTagsService.class).refreshFocusTags().compose(TransformUtils.<TagsBean>defaultSchedulers()).subscribe(new CommonSubscriber<TagsBean>() {
                @Override
                public void onSuccess(TagsBean response) {
                    if (!TextUtils.isEmpty(PreferenceUtils.GetUserIdHash())) {
                        Set<String> tagSet = new LinkedHashSet<String>();
                        for (String sTagItme : response.getData().getTags()) {
                            if (!TextUtils.isEmpty(sTagItme)) {
                                tagSet.add(sTagItme);
                            }

                        }
                        JPushInterface.setAliasAndTags(MainActivity.this, PreferenceUtils.GetUserIdHash(), tagSet, new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {

                            }
                        });
                    }
                }

                @Override
                public void onFailure(BaseBean response) {
                    Set<String> tagSet = new LinkedHashSet<String>();
                    JPushInterface.setAliasAndTags(MainActivity.this, "", tagSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {

                        }
                    });
                }
            });
        } else {
            Set<String> tagSet = new LinkedHashSet<String>();
            JPushInterface.setAliasAndTags(MainActivity.this, "", tagSet, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {

                }
            });
        }

    }


    @Override
    public void setupData() {
        mCircleFragment = ViewUtils.createFragment(DiscoveryFragment.class, false);
        Bundle bundle_movie = new Bundle();
        bundle_movie.putString("feed_type", "circle");
        mCircleFragment.setArguments(bundle_movie);
        currentFragment = mCircleFragment;
        mFragmentManager.beginTransaction().add(R.id.content_frame, mCircleFragment).commitAllowingStateLoss();
//        from_url = getIntent().getBooleanExtra("KEY_FROM_URL", false);
//        if (from_url) {
//            boolean is_to_feed = getIntent().getBooleanExtra("KEY_IS_FEED", false);
//            String local_hash = getIntent().getStringExtra("KEY_HASH");
//            if (is_to_feed) {
//                Intent intent = new Intent(MainActivity.this, FeedDetailInfoActivity.class);
//                App.GetInstance().finishClassActivity(FeedDetailInfoActivity.class);
//                intent.putExtra("KEY_FEED_HASH", local_hash);
//                MainActivity.this.startActivity(intent);
//            } else {
//                Intent intent = new Intent(MainActivity.this, CircleActivity.class);
//                App.GetInstance().finishClassActivity(CircleActivity.class);
//                intent.putExtra("KEY_CIRCLE_TITLE", "");
//                intent.putExtra("KEY_CIRCLE_HASH", local_hash);
//                MainActivity.this.startActivity(intent);
//            }
//            from_url = false;
//        }
    }

    private void refreshIntervalPushMessage() {
        ServiceFactory.GetInstance().createService(PushMessageService.class).refreshPushMessages().compose(TransformUtils.<FeedCirclePushMessageBean>defaultSchedulers()).subscribe(new Subscriber<FeedCirclePushMessageBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(FeedCirclePushMessageBean feedCirclePushMessageBean) {
                if (feedCirclePushMessageBean.getStatus() == 0) {
                    EventBus.getDefault().post(feedCirclePushMessageBean.getData());
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!TextUtils.isEmpty(PreferenceUtils.GetUserToken())){
            StartRefreshTagsAction action = new StartRefreshTagsAction();
            EventBus.getDefault().post(action);
        }
        if((!TextUtils.isEmpty(PreferenceUtils.GetUserToken()))&&(rxSubscription_long==null)){
            rxSubscription_long = Observable.interval(15, TimeUnit.SECONDS)
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Long number) {
                            refreshIntervalPushMessage();
                        }
                    });
        }
    }

    @Override
    protected void onStop() {
        if(rxSubscription_long!=null){
            if(rxSubscription_long.isUnsubscribed()){
                rxSubscription_long.unsubscribe();
                rxSubscription_long=null;
            }
        }
        super.onStop();
    }

    @Override
    public void onConfirmExit() {
        MaterialDialog confirmDialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content("您确定退出吗")
                .cancelable(false)
                .negativeText("取消")
                .positiveText("确定").onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        JPushInterface.clearAllNotifications(MainActivity.this);
//                        JPushInterface.stopPush(getApplicationContext());
                        App.GetInstance().exit();
                    }
                }).build();
        confirmDialog.show();
    }

    @Override
    public void onBackPressed() {
        onConfirmExit();
    }

    @Override
    protected void onDestroy() {
//        JPushInterface.stopPush(getApplicationContext());
        super.onDestroy();
        if(rxSubscription!=null){
            if (!rxSubscription.isUnsubscribed()) {
                rxSubscription.unsubscribe();
            }
        }
        if(rxSubscription_long!=null){
            if (!rxSubscription_long.isUnsubscribed()) {
                rxSubscription_long.unsubscribe();
                rxSubscription_long=null;
            }
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEvent(FeedCirclePushMessageEntity pushMessage) {
        if (pushMessage.isCircle() || pushMessage.isFeed()) {
            notify_tv_bottom.setVisibility(View.VISIBLE);
        } else {
            notify_tv_bottom.setVisibility(View.INVISIBLE);
        }
    }
}
